{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
    <title>
        Online Chart
    </title>
    <script src="{% static 'assets/js/webcam.min.js' %}"></script>
</head>
<body>
<div id="camera"></div>
<canvas style="display: none" id="canvas" width="480" height="320"></canvas>
<img style="display: none" id="origin" width="480" height="320">
<img id="target" width="480" height="320">
<script>
    var canvas = document.getElementById('canvas');
    var target = document.getElementById('target');
    var context = canvas.getContext('2d');
    Webcam.set({
        width: 480,
        height: 320,
        image_format: 'jpeg',
        jpeg_quality: 90
    });
    Webcam.attach('#camera');
    console.log(Webcam);
    console.log(window.location.host);

    var ws = new WebSocket("ws://" + window.location.host + "/websockettest/");
    ws.binaryType = "arraybuffer";

    ws.onopen = function () {
        console.log("开始链接");
    };

    ws.onmessage = function (evt) {
        try {
            target.src = "data:image/png;base64," + evt.data;
        } catch {
            console.log("数据异常");

        }

    };

    ws.onclose = function () {
        console.log("Closed");
    };

    ws.onerror = function (err) {
        console.log("Error: " + err);
    };

    function dataURItoBlob(dataURI) {
        var byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = unescape(dataURI.split(',')[1]);

        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        return new Blob([ia], {type: mimeString});
    }

    timer = setInterval(
        function () {
            if (Webcam.loaded) {
                Webcam.snap(function (data_uri) {
                    var origin = document.getElementById('origin');
                    origin.src = data_uri;
                    context.drawImage(origin, 0, 0, 480, 320);
                    var data = canvas.toDataURL('image/jpeg', 1.0);
                    newblob = dataURItoBlob(data);
                    ws.send(newblob);
                });
            }
        }, 1000);
</script>
</body>
</html>